from PySide2.QtGui import QTextCursor, QTextCharFormat, QColor
from PySide2.QtWidgets import QTextEdit, QFileDialog
from PySide2.QtCore import Qt
from datetime import datetime
class LogEdit(QTextEdit):
    '''
        日志记录控件
    '''
    def __init__(self):
        super().__init__()

    def Now(self):
        '''
        当前时间
        :return:
        '''
        current_time = datetime.now()
        # 格式化时间字符串
        formatted_time = current_time.strftime("[%H:%M:%S]")
        return formatted_time

    def PushLog(self,text,level='info'):
        '''
        记录日志
        :param level:
        :return:
        '''
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.End)
        # 设置不同级别的颜色
        text_format = QTextCharFormat()
        if level == "info":
            text_format.setForeground(QColor("green"))
        elif level == "warning":
            text_format.setForeground(QColor("orange"))
        elif level == "error":
            text_format.setForeground(QColor("red"))

        # 应用颜色并插入文字
        cursor.setCharFormat(text_format)
        cursor.insertText(self.Now()+text + "\n")
        self.setTextCursor(cursor)

    def SaveLog(self):
        '''
        保存日志
        :return:
        '''
        file_path, _ = QFileDialog.getSaveFileName(self, "保存日志文件", "", "Text Files (*.txt)")
        if file_path:
            with open(file_path, 'w') as file:
                file.write(self.toPlainText())